package com.coder.rental.security;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.SecureRandom;

/**
 * @author: zhanglin
 * @description:   密码加密配置类，使用BCrypt算法，密文=版本号+加密强度+随机盐值+哈希值，从123456密文中取出加密强度和盐值，根据这两个重新对明文加密可得到相同的密文哈希值，从而匹配密码
 * @date 2025/3/24
 */
@Configuration
@Data
public class PasswordConfig {
    /*
    * 加密强度参数，也就是迭代次数成本因子$06，默认是$10
    * */
    @Value("${encoder.ctype.strength}")  //$2a$06$0c/ndr5FZ87vzmlIVJdUd.sEtG0neP5cgvsSljCBQWxDCemLzp5cq
    private int strength;
    /*
    * 加密密钥
    * */
    @Value("${encoder.ctype.secret}")
    private String secret;
    /*
    * 定义BCryptPasswordEncoder的Bean容器，用于密码的加密和匹配验证
    * BCryptPasswordEncoder(strength,secureRandom);配置指定的加密强度和密钥
    * */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        return new BCryptPasswordEncoder(strength,secureRandom);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordConfig = new PasswordConfig().passwordEncoder();
        //由于[spring-security-crypto-6.0.6.jar:6.0.6]的crypto5.0+后，密文前需要添加{bcrypt}，作为id标识，否则会报There is no PasswordEncoder mapped for the id "null"
        System.out.println("{bcrypt}"+passwordConfig.encode("123456"));
        System.out.println("{bcrypt}"+passwordConfig.encode("123456"));
        // System.out.println(passwordConfig.encode("123456"));
        // System.out.println(passwordConfig.encode("123456"));
        boolean matches = passwordConfig.matches("123456", "$2a$10$wUdRJg4s9k8gatTECm3DIufA7jQzMrJJKG9bhHvKLmDWX451JOC1.");
        System.out.println("matches = "+matches);
    }
    
}
